package com.iotproject.forumservice.controller;

import com.iotproject.commonutils.R;
import com.iotproject.forumservice.entity.ForumQuestion;
import com.iotproject.forumservice.entity.vo.AddQuestionVo;
import com.iotproject.forumservice.entity.vo.UpdateQuestionVo;
import com.iotproject.forumservice.service.ForumQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/forumservice/forum-question/editQuestion")
public class EditQuestionController {

    @Autowired
    ForumQuestionService forumQuestionService;

    //发起问题
    @PostMapping("/addQuestion")
    public R addQuestion (@RequestBody AddQuestionVo addQuestionVo) {
        String title = addQuestionVo.getTitle();
        String description = addQuestionVo.getDescription();
        String tag = addQuestionVo.getTag();
        String creatorId = addQuestionVo.getCreatorId();
        if(StringUtils.isEmpty(tag)){
            tag = "个人分享";
        }
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(description) || StringUtils.isEmpty(tag) || StringUtils.isEmpty(creatorId)) {
            return R.error();
        }
        //评论数 浏览数 点赞数 默认为 0
        ForumQuestion question = new ForumQuestion();
        question.setTitle(title);
        question.setDescription(description);
        question.setCreatorId(creatorId);
        question.setTag(tag);
        question.setIsDeleted(false);
        boolean addQuestion = forumQuestionService.save(question);
        if (addQuestion) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    //修改问题
    @PostMapping("/updateQuestion")
    public R updateQuestion (@RequestBody UpdateQuestionVo updateQuestionVo) {
        String title = updateQuestionVo.getTitle();
        String description = updateQuestionVo.getDescription();
        String tag = updateQuestionVo.getTag();
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(description) || StringUtils.isEmpty(tag)) {
            return R.error();
        }
        String questionId = updateQuestionVo.getId();
        ForumQuestion forumQuestion = forumQuestionService.getById(questionId);
        if (forumQuestion == null) {
            return R.error().message("话题不存在");
        }
        forumQuestionService.updateQuestion(questionId, title, description, tag);
        return R.ok();
    }
}
